package org.example.repeater.handler.core;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;


public class ByteBufUtils {

    /**
     * Returns the number of bytes between the readerIndex of the haystack and
     * the first needle found in the haystack.  -1 is returned if no needle is
     * found in the haystack.
     */
    public static int indexOf(ByteBuf haystack, byte[] needle,boolean fristNeedle) {
        if (!fristNeedle&&haystack.getByte(0) == needle[0]) {
            haystack.readerIndex(1);
            int i = indexOf(haystack, needle, true);
            return i;
        }else {
            for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++) {
                int haystackIndex = i;
                int needleIndex;
                for (needleIndex = 0; needleIndex < needle.length; needleIndex++) {
                    if (haystack.getByte(haystackIndex) == needle[needleIndex]) {
                        haystackIndex++;
                        if (haystackIndex == haystack.writerIndex() && needleIndex != needle.length - 1) {
                            return -1;
                        }

                    } else {
                        break;
                    }
                }

                if (needleIndex == needle.length) {
                    if (fristNeedle){
                          return i - haystack.readerIndex()+1;
                    }
                    // Found the needle from the haystack!
                    return i - haystack.readerIndex();
                }
            }
        }
        return -1;
    }

    public static boolean startsWith(ByteBuf haystack, byte[] prefix) {
        for (int i = 0, j = haystack.readerIndex(); i < prefix.length; )
            if (prefix[i++] != haystack.getByte(j++))
                return false;
        return true;
    }
}